package corelayer;

import corelayer.packets.HelloPacket;
import java.io.ByteArrayInputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * パケットをデコードします。
 */
public class PacketBuilder {

    private Map<Integer, IPacketFactory> factoryMap;

    public PacketBuilder() {
        this.factoryMap = this.createDefaultFactoryMap();
    }

    protected static Map<Integer, IPacketFactory> createDefaultFactoryMap() {
        HashMap<Integer, IPacketFactory> factories = new HashMap<Integer, IPacketFactory>();
        factories.put(HelloPacket.TYPE_CODE, new HelloPacket.Factory());
        return factories;
    }

    public IPacket unpack(byte[] data) {
        DataInput di = new DataInputStream(new ByteArrayInputStream(data));
        try{
            byte type = di.readByte();
            IPacketFactory pf = this.factoryMap.get(type);
            return pf.unpack(di);
        } catch (IOException e){
            System.out.println("Failed to decode message!!");
            System.out.println(e.getMessage());
            throw new RuntimeException(e);
        }
    }
}
